package lifei.lifei.mybatis.common;


import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/*
使用JDBC访问数据库的工具类
 */
public class JdbcUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    static {
        try {
        //创建一个Properties
            Properties pro = new Properties();
        //通过反射读取properties文件的数据
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //将输入流的属性值加载到对象中
            pro.load(is);
         //获取属性的值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            throw new RuntimeException("连接失败");
        }catch (ClassNotFoundException e) {
            throw new RuntimeException("驱动类找不到");
        }
    }
    //获取链接
    public static Connection getConn(){
        Connection conn;
        try {
            conn = DriverManager.getConnection(url,user,password);
        }catch (SQLException se){
            se.printStackTrace();;
            throw new RuntimeException("SQL语句报错");
        }
        return conn;
    }
    //关闭连接
    public static <T> void clocesIO(T t){
        if (t!=null) {
            try {
                //利用反射获取class对象
                Class<?> aClass = t.getClass();
                //获取对象中方法对象
                Method method = aClass.getMethod("close");
                method.invoke(t);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("此方法不存在");
            } catch (Exception e) {
                throw new RuntimeException("权限不足");
            }
        }
    }
}
